package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

// 二叉树的前序遍历
public class LeetCodeTest0144 {

    public static void main(String[] args) {

    }

    private ArrayList<Integer> result = new ArrayList<>();

//    public List<Integer> preorderTraversal(TreeNode root) {
//        if (root == null) {
//            return result;
//        }
//        result.add(root.val);
//        if (root.left != null) {
//            preorderTraversal(root.left);
//        }
//        if (root.right != null) {
//            preorderTraversal(root.right);
//        }
//        return result;
//    }

    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) {
            return result;
        }
        Stack<TreeNode> treeNodeStack = new Stack<>();
        treeNodeStack.push(root);
        while (!treeNodeStack.isEmpty()) {
            TreeNode node = treeNodeStack.pop();
            result.add(node.val);
            if (node.right != null) {
                treeNodeStack.push(node.right);
            }
            if (node.left != null) {
                treeNodeStack.push(node.left);
            }
        }
        return result;
    }

}
